package com.wxy.care.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wxy.care.KnnUtils.Instance;
import com.wxy.care.KnnUtils.KNN;
import com.wxy.care.common.R;
import com.wxy.care.entity.Count;
import com.wxy.care.entity.CountDto;
import com.wxy.care.entity.Sensor;
import com.wxy.care.service.CountService;
import com.wxy.care.service.SensorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/knn")
public class KnnPredictController {
    @Autowired
    private CountService countService;
    @Autowired
    private SensorService sensorService;

    @Autowired
    private KNN knn;

    @GetMapping("/predict")
    public R<String> predict(String name){
        Map<String,Integer> map = new HashMap<>();
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime suitTime = localDateTime.minusMinutes(30);
        LambdaQueryWrapper <Count>queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Count::getHouseName,name)
                .gt(Count::getDate,suitTime);
        LambdaQueryWrapper<Sensor> queryWrapper1 = new LambdaQueryWrapper();
        queryWrapper1.eq(Sensor::getHouseName,name);
        for(Sensor sensor : sensorService.list(queryWrapper1)){
            map.put(sensor.getSlaveId(),sensor.getPlace());
        }
        List<Count> list = countService.list(queryWrapper);
        List<CountDto> countList = list.stream().map((item)->{
            CountDto countDto = new CountDto();
            BeanUtils.copyProperties(item,countDto);
            countDto.setPlace(map.get(item.getSlaveId()));
            return countDto;
        }).collect(Collectors.toList());
        double[] knnPredict = new double[40];
        countList.stream().map((item)->{
            knnPredict[item.getPlace()] += 1;
            return item;
        });
        String predict = knn.predict(new Instance(knnPredict,""));
        return R.success(predict);
    }

}
